import GROUP_DATA from '../../utils/groups.js'
import storage from '../../utils/storage.js'

Page({
  data: {
    wordGroups: [],
    learningProgress: 0,
    completedGroups: 0,
    totalGroups: 0,
    recentGroups: [], // 最近学习的分组
    newGroups: [] // 未开始学习的分组
  },

  onLoad() {
    this.loadGroupsData();
  },

  loadGroupsData() {
    // 获取所有分组进度
    const groupsProgress = storage.getAllGroupsProgress();
    
    // 处理分组数据
    const groups = GROUP_DATA.map(item => {
      const progress = groupsProgress[item.group.group_id] || {};
      return {
        id: item.group.group_id,
        name: item.group.word_chinese,
        image: item.group.word_image,
        completed: progress.isCompleted || false,
        lastStudyTime: progress.lastStudyTime || 0,
        currentWord: progress.currentWord,
        hasWordTest: progress.wordTestResults && Object.keys(progress.wordTestResults).length > 0,
        hasListeningTest: progress.listeningTestResults && Object.keys(progress.listeningTestResults).length > 0,
        status: progress.isCompleted ? 'completed' : (progress.lastStudyTime ? 'learning' : 'new')
      };
    });

    // 分离最近学习和新分组
    const recentGroups = groups
      .filter(group => group.lastStudyTime > 0)
      .sort((a, b) => b.lastStudyTime - a.lastStudyTime);
    
    const newGroups = groups.filter(group => !group.lastStudyTime);

    this.setData({
      wordGroups: groups,
      recentGroups,
      newGroups,
      totalGroups: groups.length,
      completedGroups: groups.filter(group => group.completed).length
    }, () => {
      this.calculateProgress();
    });
  },

  calculateProgress() {
    const total = this.data.wordGroups.length;
    const completed = this.data.wordGroups.filter(group => group.completed).length;
    
    this.setData({
      totalGroups: total,
      completedGroups: completed,
      learningProgress: (completed / total) * 100
    });
  },

  goToWordLearning(e) {
    const groupId = e.currentTarget.dataset.groupId;
    wx.navigateTo({
      url: `/pages/wordLearning/wordLearning?groupId=${groupId}`
    });
  },

  goToSettings() {
    wx.navigateTo({
      url: '/pages/settings/settings'
    });
  },

  onShow() {
    // 每次页面显示时重新加载数据
    this.loadGroupsData();
  }
}); 